package com.futong.cloud.function;

import com.alibaba.fastjson.JSONPath;
import com.futong.cloud.action.ActionConsumer;
import com.futong.cloud.dao.CrudMapper;
import com.futong.cloud.dao.entity.ActionFiled;
import com.futong.cloud.utils.ContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Arrays;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class Crud {
    public static ActionConsumer inserts= context -> {
        //解析基本信息
        String table = null;int size=0;
        List<String> columns=new ArrayList<>();
        List<ActionFiled> fileds=new ArrayList<>();
        for (ActionFiled filed : context.actionModel.getFileds()) {
            if(StringUtils.isEmpty(filed.getDbPath()))continue;
            String[] split = filed.getDbPath().split("\\.");
            columns.add(split[1]);
            fileds.add(filed);
            if(StringUtils.isEmpty(table))table=split[0];
            if(size==0&&filed.getContextPath().contains("[index]")) {
                size = (int) JSONPath.eval(context, StringUtils.substringBefore(filed.getContextPath(),"[index]")+".size()");
            }
        }
        //封装sql_values信息
        StringBuffer values=new StringBuffer();
        for (int i = 0; i < size; i++) {
            values.append("(");
            for (ActionFiled filed : fileds) {
                String filedPath;
                if(StringUtils.isEmpty(filedPath=filed.getContextPath())){
                    values.append("null").append(",");
                    continue;
                }
                filedPath=filedPath.replace("[index]","["+i+"]");
                String value=null;
                if("id".equalsIgnoreCase(filed.getFiled())){
                    Object obj = ContextUtils.getValue(context, filedPath);
                    if(obj instanceof ArrayList){
                        ArrayList<String> list= (ArrayList) obj;
                        value= list.stream().collect(Collectors.joining("-"));
                        value=context.getRequest().getString("clientId")+"-"+value;
                    }
                }else{
                    value = ContextUtils.getValueStr(context, filedPath);
                }
                values.append("'").append(value).append("'").append(",");
            }
            values.deleteCharAt(values.length()-1);
            values.append(")").append(",");
        }
        values.deleteCharAt(values.length()-1);
        //入库
        int count = CrudMapper.Mappers.crud.insert(table, columns, values.toString());
        context.setResponse(count);
    };
}
